﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;

namespace SpectralCamera.Extend
{
    public class CMDHelper
    {
        // 配置目标参数
        private const string TargetInterfaceIp = "192.168.0.3";
        private const string TargetIp = "192.168.0.4";
        private const string TargetMac = "00-0a-35-01-fe-c0";

        public static void SetLocalIpCheck()
        {
            if (!IsAdministrator())
            {
                RestartAsAdmin();
                return;
            }

            try
            {
                var interfaceIndex = GetInterfaceIndex(TargetInterfaceIp);
                if (!interfaceIndex.HasValue)
                {
                    Console.WriteLine($"未找到 IP 为 {TargetInterfaceIp} 的网络接口");
                    return;
                }

                if (!CheckArpEntry(interfaceIndex.Value, TargetIp, TargetMac))
                {
                    AddArpEntry(interfaceIndex.Value, TargetIp, TargetMac);
                    Console.WriteLine("已成功添加 ARP 条目");
                }
                else
                {
                    Console.WriteLine("ARP 条目已存在");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"操作失败: {ex.Message}");
            }
        }

        #region 权限管理
        private static bool IsAdministrator()
        {
            var identity = WindowsIdentity.GetCurrent();
            var principal = new WindowsPrincipal(identity);
            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }

        private static void RestartAsAdmin()
        {
            var exePath = Assembly.GetExecutingAssembly().Location;
            var startInfo = new ProcessStartInfo
            {
                FileName = exePath,
                UseShellExecute = true,
                Verb = "runas"
            };

            try
            {
                Process.Start(startInfo);
            }
            catch (Win32Exception)
            {
                // 用户拒绝 UAC 提示
            }
            Environment.Exit(0);
        }
        #endregion

        #region 网络接口处理
        private static int? GetInterfaceIndex(string ipAddress)
        {
            foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
            {
                foreach (var addr in ni.GetIPProperties().UnicastAddresses)
                {
                    if (addr.Address.ToString() == ipAddress)
                    {
                        var ipv4Properties = ni.GetIPProperties().GetIPv4Properties();
                        return ipv4Properties?.Index;
                    }
                }
            }
            return null;
        }
        #endregion

        #region ARP 条目管理
        private static bool CheckArpEntry(int interfaceIndex, string targetIp, string targetMac)
        {
            var psi = new ProcessStartInfo
            {
                FileName = "arp",
                Arguments = "-a",
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };

            using (var process = Process.Start(psi))
            {
                var output = process.StandardOutput.ReadToEnd();
                process.WaitForExit();

                return ParseArpOutput(output, interfaceIndex, targetIp, targetMac);
            }
        }

        private static bool ParseArpOutput(string output, int interfaceIndex, string targetIp, string targetMac)
        {
            var lines = output.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            var targetHeader = $"接口: {TargetInterfaceIp} --- 0x{interfaceIndex:X}";
            var foundInterface = false;

            foreach (var line in lines)
            {
                if (line.StartsWith("接口:"))
                {
                    foundInterface = line.Contains(targetHeader);
                    continue;
                }

                if (foundInterface && line.Trim().Length > 0)
                {
                    var parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    if (parts.Length >= 2 &&
                        parts[0] == targetIp &&
                        parts[1].Equals(targetMac, StringComparison.OrdinalIgnoreCase))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        private static void AddArpEntry(int interfaceIndex, string ip, string mac)
        {
            var psi = new ProcessStartInfo
            {
                FileName = "netsh",
                Arguments = $"interface ipv4 add neighbors {interfaceIndex} \"{ip}\" \"{mac}\"",
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };

            using (var process = Process.Start(psi))
            {
                process.WaitForExit();

                if (process.ExitCode != 0)
                {
                    var error = process.StandardError.ReadToEnd();
                    throw new Exception($"命令执行失败: {error}");
                }
            }
        }
        #endregion
    }
}
